#pragma once

// MySQL 版本

#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <fstream>

#include <cassert>

#include "../comm/log.hpp"
#include "../comm/util.hpp"

#include "include/mysql.h"

namespace dsh_model
{
    using namespace dsh_util;
    using namespace dsh_log;

    struct Question
    {
        std::string number; // 题目编号
        std::string title;  // 题目标题
        std::string star;   // 难度
        std::string desc;   // 题目的描述
        std::string header; // 题目预设给用户在线编译器的代码
        std::string tail;   // 题目的测试用例，要和header拼接
        int cpu_limit;      // cpu时间限制，单位为S
        int mem_limit;      // 空间限制，单位为KB
    };

    const std::string oj_questions = "oj_questions";
    const std::string host = "127.0.0.1";
    const std::string user = "oj_server_client";
    const std::string passwd = "123456";
    const std::string db = "db";
    const int port = 3306; 

    class Model
    {
    public:
        Model()
        {}
        ~Model()
        {}

        bool QueryMySql(const std::string& sql, std::vector<Question>* out)
        {
            // 创建MySQL句柄
            MYSQL* my = mysql_init(nullptr);

            if (nullptr == mysql_real_connect(my, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0))
            {
                LOG(FATAL) << "连接数据库失败！" << std::endl;
                return false;
            }

            // 关闭mysql连接
            mysql_close(my);
        }

        bool GetAllQuestions(std::vector<Question>* out)
        {
            const std::string sql = "select * from " + oj_questions;
            return QueryMySql(sql, out);
        }

        bool GetOneQuestion(const std::string& number, Question* q)
        {
            bool res = false;
            const std::string sql = "select * from " + oj_questions + " where id = " + number;
            std::vector<Question> result;
            if (QueryMySql(sql, &result))
            {
                if (result.size() == 1)
                {
                    *q = result[0];
                    res = true;
                }
            }
            return res;
        }

    };
}